package com.hrm.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 检查用户是否已经完成登录
 */

@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    // 路径匹配器    支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher(); // 它可以把*当做通配符

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        log.info("拦截到请求：{}", requestURI);

        //1定义不需要处理的请求路径
        String[] urls = new String[]{
                "/logout",
                "/user/login",
                "/user/register",
                "/common/code",
                "/res/**",
                "/favicon.ico",
                "/user/checkLoginName"
        };
        // 2判断本次请求是否需要处理
        boolean check = check(urls, requestURI);
        // 3不需要处理，放行
        if (check) {
            log.info("不需要处理的请求：{}", requestURI);
            request.setCharacterEncoding("utf-8");
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=utf-8");
            filterChain.doFilter(request, response);
            return;
        }

        // 4 - 1 判断是否已登录
//        if (request.getSession().getAttribute("user") != null) {
        log.info("用户已登录,用户为{}", request.getSession().getAttribute("user"));
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        filterChain.doFilter(request, response);
        return;
//        }

//         5未登录，则返回未登录结果，通过输出流方式调用前端进行重定向，对于异步请求，这里解决不了，在前端解决
//        log.info("用户未登录");
//        PrintWriter out = response.getWriter();
//        out.println("<html><script>if (window != top) {");
//        out.println("top.location.href = \"/res/user/login.jsp\"}");
//        out.println("else {location.href = \"/res/user/login.jsp\"}");
//        out.println("</script></html>");
    }

    /**
     * 路径匹配，检查本次是否放行
     *
     * @param urls
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
